package com.hotel.front;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.Util;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.labs.repackaged.org.json.JSONException;
import com.google.gson.Gson;
import com.hotel.BL.POSCategoryLogic;
import com.hotel.BL.POSItemLogic;
import com.hotel.BL.POSLogic;
import com.hotel.BL.POSTaxLogic;
import com.hotel.BL.POSUnitLogic;

import data.POS;
import data.POSCategory;
import data.POSItem;
import data.POSTax;
import data.POSUnit;
import data.passingData.ResultData;

@SuppressWarnings("serial")
public class POSItemService extends HttpServlet {

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		try {
			String func = req.getParameter("func");
			if (func.equals("loadPOSTax")) {
				LoadPOSTax(req, resp);
			}
			else if (func.equals("loadPOSUnit")) {
				LoadPOSUnit(req, resp);
			}
			else if (func.equals("loadCategory")){
				loadCategory(req, resp);
			}
			else if (func.equals("loadItem")){
				loadItem(req, resp);
			}
			else if(func.equals("setFav")){
				setFav(req,resp);
			}
			else if(func.equals("getAllPOSItem")){
				GetAllPOSItem(req,resp);
			}
			else if(func.equals("getItemById")){
				GetItemById(req,resp);
			}
			else if(func.equals("getOptionPos")){
				GetForOptionAddProductPOS(req,resp);
			}
			else if(func.equals("getOption")){
				GetForOptionAddProduct(req,resp);
			}
			else if(func.equals("getPOSItemById")){
				GetPOSItemById(req,resp);
			}
			else if(func.equals("addPOSItem")){
				AddPOSItem(req,resp);
			}
			else if(func.equals("editPOSItem")){
				EditPOSItem(req,resp);
			}
			else if(func.equals("editStatusPOSItemById")){
				ChangeStatus(req,resp);
			}
			else if(func.equals("delPOSItem")){
				DeletePOSItem(req,resp);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void LoadPOSTax(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		HttpSession session = req.getSession(true);
		long hotelId = 1;
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) session.getAttribute("hotelId");
		List<POSTax> obj = new POSTaxLogic(req,resp).GetAllPOSTax(hotelId);
		List<HashMap<String,Object>> list = new ArrayList<HashMap<String,Object>>();
		for(POSTax p: obj)
		{
			HashMap<String,Object> hash = Util.toHashmap(p);
			hash.remove("key");
			hash.put("id", p.getId());
			list.add(hash);
		}
		
		Gson gson = new Gson();

		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(list));
	}
	private void LoadPOSUnit(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		HttpSession session = req.getSession(true);
		long hotelId = 1;
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) session.getAttribute("hotelId");
		List<POSUnit> obj = new POSUnitLogic(req,resp).GetAllPOSUnit(hotelId);
		List<HashMap<String,Object>> list = new ArrayList<HashMap<String,Object>>();
		for(POSUnit p: obj)
		{
			HashMap<String,Object> hash = Util.toHashmap(p);
			hash.remove("key");
			hash.put("id", p.getId());
			list.add(hash);
		}
		
		Gson gson = new Gson();

		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(list));
	}
	private void loadCategory(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		long posId = Long.parseLong(req.getParameter("posId"));
		POSCategoryLogic catLogic = new POSCategoryLogic(req,resp);
		List<POSCategory> obj = catLogic.GetAllCategoryInPOS(posId);
		List<HashMap<String,Object>> list = new ArrayList<HashMap<String,Object>>();
		for(POSCategory p: obj)
		{
			HashMap<String,Object> hash = Util.toHashmap(p);
			hash.remove("key");
			hash.put("id", p.getId());
			list.add(hash);
		}
		
		Gson gson = new Gson();

		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(list));
	}
	private void loadItem(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		HttpSession session=req.getSession(true);	
		long hotelId = (Long) session.getAttribute("hotelId");
		long posId = Long.parseLong(req.getParameter("posId"));
		POSItemLogic itemLogic = new POSItemLogic(req,resp);
		List<POSItem> obj = itemLogic.GetAllPOSItemInPOS(hotelId,posId);
		List<HashMap<String,Object>> list = new ArrayList<HashMap<String,Object>>();
		for(POSItem p: obj)
		{
			HashMap<String,Object> hash = Util.toHashmap(p);
			hash.remove("key");
			hash.put("id", p.getId());
			list.add(hash);
		}
		Gson gson = new Gson();
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(list));
	}
	
	//localhost:8080/POSItemService?func=setFav&item=&set=true
	private void setFav(HttpServletRequest req, HttpServletResponse resp) throws IOException{
		long hotelId = 1;
		HttpSession session = req.getSession(true);
		if (session.getAttribute("hotelId") != null)
			hotelId = (Long) session.getAttribute("hotelId");
		
		long itemId = Long.parseLong(req.getParameter("item"));
		boolean setF = Boolean.parseBoolean(req.getParameter("set"));
		POSItemLogic posItemLogic = new POSItemLogic(req,resp);
		POSItem posItem = posItemLogic.GetPOSItem(itemId);
		posItem.setFavourite((setF)?posItemLogic.GetMaxPOSItemFavId(hotelId)+1:0);
		posItem = posItemLogic.UpdatePOSItem(posItem);
		Gson gson = new Gson();

		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(posItem));
	}
	
	private void GetAllPOSItem(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{	
		HttpSession session=req.getSession(true);	
		long hotelId = (Long) session.getAttribute("hotelId");
		boolean isIncludetax = (Boolean) session.getAttribute("isIncludetax");
		long offset = Long.parseLong(req.getParameter("offset"));
		long line = Long.parseLong(req.getParameter("line"));
		long pointer = Long.parseLong(req.getParameter("pagePointer"));
		String cateId = req.getParameter("cateId");
		long posId =Long.parseLong(req.getParameter("posId"));
		List<POSItem> obj = new POSItemLogic(req,resp).GetAllPOSItem4AdminLimit(hotelId,offset,line,cateId,posId);
		double dataSize = new POSItemLogic(req,resp).GetAllPOSItem4Admin(hotelId,cateId,posId).size();
		List<HashMap<String,Object>> product = new ArrayList<HashMap<String,Object>>();
		POSLogic posLogic = new POSLogic(req,resp);
		for(int i=0;i<obj.size();i++){
			HashMap<String,Object> productSet = new HashMap<String,Object>();
			POS pos = posLogic.GetPOS(obj.get(i).getPOSId());
			productSet.put("id", obj.get(i).getId());
			productSet.put("avaliable", obj.get(i).isAvaliable());
			productSet.put("categoryString", obj.get(i).getCategoryString());
			productSet.put("categoryTitle", obj.get(i).getCategory().getTitle());
			productSet.put("hotelId", obj.get(i).getHotelId());
			productSet.put("isFavourite", obj.get(i).getFavourite());
			if(obj.get(i).getKitchenString()!=null){
				productSet.put("kitchenString", obj.get(i).getKitchenString());
				productSet.put("kitchenTitle", obj.get(i).getKitchen().getTitle());
			}else{
				productSet.put("kitchenString", "");
				productSet.put("kitchenTitle", "");
			}
			productSet.put("posId", obj.get(i).getPOSId());
			productSet.put("posTitle",pos.getTitle());
			double percentTax = 0.0;
			double fixTax = 0.0;
			if(obj.get(i).getTaxString()!=null){
				if(!obj.get(i).getTaxString().equals("")){
					for(int t =0;t<obj.get(i).getTax().size();t++){
						if(obj.get(i).getTax().get(t).isPercent()==true)
							percentTax += obj.get(i).getTax().get(t).getCurrencyValue();
						else
							fixTax += obj.get(i).getTax().get(t).getCurrencyValue();
					}
				}
			}
			double taxsetprice = 0.0;
			taxsetprice = ((obj.get(i).getPrice()*percentTax)/100)+fixTax;
			double priceuse = 0.0;
			if(isIncludetax==true){
				priceuse = obj.get(i).getPrice()+taxsetprice;
			}else{
				priceuse = obj.get(i).getPrice();
			}
			//priceuse = obj.get(i).getPrice()+taxsetprice;
			productSet.put("price",priceuse);
			productSet.put("productId",obj.get(i).getProductId());
			productSet.put("status",obj.get(i).isStatus());
			productSet.put("title",obj.get(i).getTitle());
			productSet.put("unitString",obj.get(i).getUnitString());
			productSet.put("unitTitle",obj.get(i).getUnit().getTitle());
			product.add(productSet);
		}
		
		
		Gson gson = new Gson();
		List<Object> rsObj = Arrays.asList(dataSize,pointer,line,product);
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(rsObj));
	}
	
	private void GetItemById(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{	
		long itemId = (Long) Long.parseLong(req.getParameter("itemId"));
		POSItemLogic posItemLogic = new POSItemLogic(req,resp);
		POSItem obj = posItemLogic.GetPOSItem(itemId);
		Gson gson = new Gson();
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(obj));
	}
	
	private void GetForOptionAddProductPOS(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{	
		HttpSession session=req.getSession(true);	
		long hotelId = (Long) session.getAttribute("hotelId");
		long posId = (Long) Long.parseLong(req.getParameter("posId"));
		Object pospoint = new POSLogic(req,resp).GetAllPOS(hotelId);
		Object categoryInPos = new POSCategoryLogic(req,resp).GetAllCategories(hotelId,posId);
		Object unit = new POSUnitLogic(req,resp).GetAllPOSUnit(hotelId);
		List<HashMap<String,Object>> option = new ArrayList<HashMap<String,Object>>();
		HashMap<String,Object> optionset = new HashMap<String,Object>();
		optionset.put("pospoint", pospoint);
		optionset.put("category", categoryInPos);
		optionset.put("unit", unit);
		option.add(optionset);
		Gson gson = new Gson();
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(option));
	}
	
	private void GetForOptionAddProduct(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{	
		HttpSession session=req.getSession(true);	
		long hotelId = (Long) session.getAttribute("hotelId");
		long posId = (Long) Long.parseLong(req.getParameter("posId"));
		//long cateId = (Long) Long.parseLong(req.getParameter("cateId"));
		Object pospoint = new POSLogic(req,resp).GetAllPOS(hotelId);
		//POSCategory category = null;
		POSCategoryLogic posCategoryLogic = new POSCategoryLogic(req,resp);
		POSLogic posLogic = new POSLogic(req,resp);
		List<HashMap<String,Object>> taxCate = new ArrayList<HashMap<String,Object>>();
		POS posData = posLogic.GetPOS(posId);
		if(posData.getListPOSTaxString()!=null&&!posData.getListPOSTaxString().equals("")){
			String[] listpostax = posData.getListPOSTaxString().split(",");
			for(int i =0;i<listpostax.length;i++){
				POSTax idTax = new POSTaxLogic(req,resp).GetPOSTax(Long.parseLong(listpostax[i]));
				HashMap<String,Object> taxset = new HashMap<String,Object>();
				taxset.put("currencyValue",idTax.getCurrencyValue());
				taxset.put("taxTitle",idTax.getTitle());
				taxset.put("taxId",idTax.getId());
				taxset.put("isPercent", idTax.isPercent());
				taxCate.add(taxset);
			}
		}
		List<POSCategory> categoryInPos = posCategoryLogic.GetAllCategories(hotelId,posId);
		List<HashMap<String,Object>> categoryParent = new ArrayList<HashMap<String,Object>>();
		for(int i = 0;i<categoryInPos.size();i++){
			int countparent = 0;
			boolean checkfor = true;
			HashMap<String,Object> categoryParentSet = new HashMap<String,Object>();
			categoryParentSet.put("avaliable", categoryInPos.get(i).isAvaliable());
			categoryParentSet.put("hotelId", hotelId);
			categoryParentSet.put("id", categoryInPos.get(i).getId());
			categoryParentSet.put("parentCategory", categoryInPos.get(i).getParentCategory());
			long cateIdCheck = categoryInPos.get(i).getParentCategory();
			while(checkfor){
				if(cateIdCheck!=0){
					countparent++;
					POSCategory categoryCheckP = posCategoryLogic.GetPOSCategory(cateIdCheck);
					if(categoryCheckP.getParentCategory()!=0){
						cateIdCheck = categoryCheckP.getParentCategory();
						countparent++;
					}else{
						checkfor = false;
					}
				}else{
					checkfor = false;
				}
		    }
			categoryParentSet.put("countparentCategory", countparent);
			categoryParentSet.put("posId", categoryInPos.get(i).getPOSId());
			categoryParentSet.put("status", categoryInPos.get(i).isStatus());
			categoryParentSet.put("subCategoryString", categoryInPos.get(i).getSubCategoryString());
			categoryParentSet.put("title", categoryInPos.get(i).getTitle());
			categoryParent.add(categoryParentSet);
		}
		Object unit = new POSUnitLogic(req,resp).GetAllPOSUnit(hotelId);
		List<HashMap<String,Object>> option = new ArrayList<HashMap<String,Object>>();
		HashMap<String,Object> optionset = new HashMap<String,Object>();
		optionset.put("pospoint", pospoint);
		optionset.put("category", categoryParent);
		optionset.put("unit", unit);
		optionset.put("taxcate", taxCate);
		option.add(optionset);
		Gson gson = new Gson();
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(option));
	}
	
	private void GetPOSItemById(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{	
		HttpSession session=req.getSession(true);
		long hotelId = (Long) session.getAttribute("hotelId");
		long id = Long.parseLong(req.getParameter("id"));
		POSItem obj = new POSItemLogic(req,resp).GetPOSItem(id);
		HashMap<String,Object> productSet = new HashMap<String,Object>();
		productSet.put("avaliable", obj.isAvaliable());
		productSet.put("categoryString", obj.getCategoryString());
		productSet.put("description", obj.getDescription());
		productSet.put("hotelId", obj.getHotelId());
		productSet.put("id", obj.getId());
		productSet.put("isFavourite", obj.getFavourite());
		productSet.put("posId", obj.getPOSId());
		productSet.put("productId", obj.getProductId());
		productSet.put("status", obj.isStatus());
		productSet.put("taxString", obj.getTaxString());
		productSet.put("price", obj.getPrice());
		List<HashMap<String,Object>> taxCate = new ArrayList<HashMap<String,Object>>();
		if(obj.getTaxString()!=null&&!obj.getTaxString().equals("")){
			for(int i =0;i<obj.getTax().size();i++){
				HashMap<String,Object> taxset = new HashMap<String,Object>();
				POSTax idTax = obj.getTax().get(i);
				taxset.put("currencyValue",idTax.getCurrencyValue());
				taxset.put("taxTitle",idTax.getTitle());
				taxset.put("taxId",idTax.getId());
				taxset.put("isPercent", idTax.isPercent());
				taxCate.add(taxset);
			}
		}
		productSet.put("taxobj", taxCate);
		
		List<HashMap<String,Object>> taxAllCate = new ArrayList<HashMap<String,Object>>();
		new POSTaxLogic(req,resp).GetAllPOSTax(hotelId);
		long cateId = Long.parseLong(obj.getCategoryString());
		new POSCategoryLogic(req,resp).GetPOSCategory(cateId);
		productSet.put("taxAllObj", taxAllCate);
		productSet.put("title", obj.getTitle());
		productSet.put("unitString", obj.getUnitString());
		Gson gson = new Gson();
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(productSet));
	}
	
	private void AddPOSItem(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{	
		HttpSession session=req.getSession(true);
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		long hotelId = (Long) session.getAttribute("hotelId");
		long pospoint = Long.parseLong(req.getParameter("pospoint"));
		boolean isIncludetax = (Boolean) session.getAttribute("isIncludetax");
		String title = req.getParameter("title");
		String idproduct = req.getParameter("idproduct");
		String favourite = req.getParameter("favourite");
		String categoryproduct = req.getParameter("categoryproduct");
		String taxuse = req.getParameter("taxuse");
		String[] taxuseSplit = taxuse.split(",");
		double taxPercent = 0.0;
		double fixtax = 0.0;
		double price = 0.0;
		POSTaxLogic posTaxLogic = new POSTaxLogic(req,resp);
		if(!taxuse.equals("")){
			for(int i=0;i<taxuseSplit.length;i++){
				long taxId = Long.parseLong(taxuseSplit[i]);
				POSTax obj = posTaxLogic.GetPOSTax(taxId);
				if(obj.isPercent()==true){
					taxPercent += obj.getCurrencyValue();
				}else{
					fixtax += obj.getCurrencyValue();
				}
			}
		}
		Double priceproduct =Double.valueOf(req.getParameter("priceproduct"));
		double tax =0.0;
		tax = ((priceproduct*taxPercent)/100)+fixtax;
		if(isIncludetax==true){
			priceproduct = priceproduct+tax;
			price = (priceproduct - fixtax)*100/(100+taxPercent);
			priceproduct = price;
		}else{
			price = (priceproduct - fixtax)*100/(100+taxPercent);
			priceproduct = price;
		}
		String unitproduct = req.getParameter("unitproduct");
		String cateId = req.getParameter("cateId");
		String description = req.getParameter("description");
		Object obj = new POSItemLogic(req,resp).AddPOSUnit(hotelId,pospoint,title,idproduct,favourite,categoryproduct,priceproduct,unitproduct,taxuse,cateId,description);
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(obj));
	}
	
	private void EditPOSItem(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		long pospoint = Long.parseLong(req.getParameter("pospoint"));
		long unitId = Long.parseLong(req.getParameter("id"));
		String title = req.getParameter("title");
		String idproduct = req.getParameter("idproduct");
		String favourite = req.getParameter("favourite");
		String categoryproduct = req.getParameter("categoryproduct");
		Double priceproduct =Double.valueOf(req.getParameter("priceproduct"));
		String unitproduct = req.getParameter("unitproduct");
		String taxuse = req.getParameter("taxuse");
		String cateId = req.getParameter("cateId");
		String description = req.getParameter("description");
		Object obj = new POSItemLogic(req,resp).EditPOSItem(unitId,pospoint,title,idproduct,favourite,categoryproduct,priceproduct,unitproduct,taxuse,cateId,description);
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(obj));
	}
	
	private void ChangeStatus(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		long itemId = Long.parseLong(req.getParameter("itemId"));
		Object obj = new POSItemLogic(req,resp).ChangeStatus(itemId);
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(obj));
	}
	
	private void DeletePOSItem(HttpServletRequest req, HttpServletResponse resp) throws IOException, JSONException, ServletException, EntityNotFoundException
	{
		Gson gson = new Gson();
		String sessionCheck = Util.checkSessionEntity(req,resp);
		if(sessionCheck==null||sessionCheck.equals("")){
			resp.setContentType("text/plain; charset=UTF-8");
			resp.getWriter().println(gson.toJson(new ResultData(false)));
			return;
		}
		String unitIdList = req.getParameter("itemId");
		for(int i = 0; i < unitIdList.split(",").length ; i++){
			new POSItemLogic(req,resp).DeletePOSItem(Long.parseLong(unitIdList.split(",")[i]));
		}
		resp.setContentType("text/plain; charset=UTF-8");
		resp.getWriter().println(gson.toJson(true));
	}
}